import os
import shutil
import threading

##############################
import basicConfig
from src import logPro, ascPro

# 定义文件夹路径的映射
FOLDER_PATH_MAP = {
    "ASC_FILE_DIR": basicConfig.ASC_FILE_DIR,
    "TEMP_FILE_DIR": basicConfig.TEMP_FILE_DIR,
    "SAVE_FILE_DIR": basicConfig.SAVE_FILE_DIR
}


def clear_files(target="ASC_FILE_DIR"):
    """
    清除指定文件夹内的所有内容。

    :param target:ASC_FILE_DIR    清除上传文件残留(default:ASC_FILE_DIR)
    :param target:TEMP_FILE_DIR   清除临时文件
    :param target:SAVE_FILE_DIR   清除默认保存目录文件
    """
    if target not in FOLDER_PATH_MAP:
        raise ValueError(f"Invalid target: {target}. Must be one of {list(FOLDER_PATH_MAP.keys())}")

    folder_path = FOLDER_PATH_MAP[target]
    for filename in os.listdir(folder_path):
        file_path = os.path.join(folder_path, filename)
        try:
            if os.path.isfile(file_path) or os.path.islink(file_path):
                os.unlink(file_path)  # 删除文件或符号链接
            elif os.path.isdir(file_path):
                shutil.rmtree(file_path)  # 递归删除文件夹
        except Exception as e:
            logPro.produce_logs("error", "删除失败 %s. 原因: %s" % (file_path, e))
    logPro.produce_logs("info", f"{folder_path}内的文件已删除")


def clear_all():
    """
    清除所有残留文件

    """
    for path in FOLDER_PATH_MAP:
        clear_thrad = threading.Thread(target=clear_files, args=(path,))
        clear_thrad.start()
        clear_thrad.join()
    logPro.produce_logs("info", "已删除所有缓存文件")
    ascPro.message_show("info", "已删除所有缓存文件")
